import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import { PermissionUtils } from '../src/constants/permissions';
import { ALL_PERMISSIONS } from '../src/constants/permissions';

const prisma = new PrismaClient();

async function main() {
  console.log('开始初始化数据库...');

  // 创建基础权限 - 使用权限常量动态获取信息
  const allPermissionCodes = PermissionUtils.getAllPermissions();
  const permissions = allPermissionCodes.map(code => ({
    name: PermissionUtils.getPermissionName(code),
    code: code,
    description: PermissionUtils.getPermissionDescription(code),
    module: PermissionUtils.getPermissionModule(code),
  }));

  console.log('创建权限...');
  
  // 先清理所有现有的权限和角色权限关联
  console.log('清理现有的权限数据...');
  await prisma.rolePermission.deleteMany({});
  await prisma.permission.deleteMany({});
  
  // 创建所有权限
  console.log(`创建 ${permissions.length} 个权限...`);
  for (const permission of permissions) {
    await prisma.permission.upsert({
      where: { code: permission.code },
      update: permission,
      create: permission,
    });
  }

  // 创建基础角色
  console.log('创建角色...');
  const adminRole = await prisma.role.upsert({
    where: { name: '超级管理员' },
    update: {},
    create: {
      name: '超级管理员',
      description: '拥有所有权限的超级管理员角色',
      status: 'ACTIVE',
    },
  });

  const userRole = await prisma.role.upsert({
    where: { name: '普通用户' },
    update: {},
    create: {
      name: '普通用户',
      description: '基础用户角色',
      status: 'ACTIVE',
    },
  });

  // 为超级管理员角色分配所有权限
  console.log('分配权限...');
  const allPermissions = await prisma.permission.findMany();
  
  for (const permission of allPermissions) {
    await prisma.rolePermission.upsert({
      where: {
        roleId_permissionId: {
          roleId: adminRole.id,
          permissionId: permission.id,
        },
      },
      update: {},
      create: {
        roleId: adminRole.id,
        permissionId: permission.id,
      },
    });
  }

  // 为普通用户角色分配基础权限
  const basicPermissions = await prisma.permission.findMany({
    where: {
      code: {
        in: [ALL_PERMISSIONS.USER_READ, ALL_PERMISSIONS.SYSTEM_CONFIG_READ],
      },
    },
  });

  for (const permission of basicPermissions) {
    await prisma.rolePermission.upsert({
      where: {
        roleId_permissionId: {
          roleId: userRole.id,
          permissionId: permission.id,
        },
      },
      update: {},
      create: {
        roleId: userRole.id,
        permissionId: permission.id,
      },
    });
  }

  // 创建超级管理员用户
  console.log('创建超级管理员用户...');
  const hashedPassword = await bcrypt.hash('admin123', 12);
  
  const adminUser = await prisma.user.upsert({
    where: { username: 'admin' },
    update: {},
    create: {
      username: 'admin',
      email: 'admin@offgrid.com',
      password: hashedPassword,
      realName: '系统管理员',
      status: 'ACTIVE',
    },
  });

  // 为超级管理员用户分配超级管理员角色
  await prisma.userRole.upsert({
    where: {
      userId_roleId: {
        userId: adminUser.id,
        roleId: adminRole.id,
      },
    },
    update: {},
    create: {
      userId: adminUser.id,
      roleId: adminRole.id,
    },
  });

  // 创建系统配置
  console.log('创建系统配置...');
  const systemConfigs = [
    {
      key: 'site_name',
      value: 'OffGrid 后台管理系统',
      description: '网站名称',
      type: 'STRING' as const,
    },
    {
      key: 'site_description',
      value: '基于 TypeScript + Express + MySQL + Prisma 构建的现代化后台管理系统',
      description: '网站描述',
      type: 'STRING' as const,
    },
    {
      key: 'user_registration_enabled',
      value: 'true',
      description: '是否允许用户注册',
      type: 'BOOLEAN' as const,
    },
    {
      key: 'max_login_attempts',
      value: '5',
      description: '最大登录尝试次数',
      type: 'NUMBER' as const,
    },
    {
      key: 'session_timeout',
      value: '3600',
      description: '会话超时时间（秒）',
      type: 'NUMBER' as const,
    },
  ];

  for (const config of systemConfigs) {
    await prisma.systemConfig.upsert({
      where: { key: config.key },
      update: {},
      create: config,
    });
  }

  console.log('数据库初始化完成！');

  console.log('作品数据创建完成！');
  console.log('超级管理员账户：');
  console.log('用户名：admin');
  console.log('密码：admin123');
  console.log('邮箱：admin@offgrid.com');
  console.log('已创建演出数据用于测试');
}

main()
  .catch((e) => {
    console.error('数据库初始化失败:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  }); 